/**
* 教员管理
*/
<template>
  <el-form v-loading="loading" :model="formData" :rules="isEditPage ? formRules : {}" ref="formRef" label-width="120px"
    :scroll-to-error="true">
    <vp-card v-if="type != 'editQulity'">
      <el-row style="flex: 1;">
        <vp-col :span="3">
          <el-form-item prop="rydaBh">
            <template #label><vp-label zh="编号" en="Number" align="left" /></template>
            <el-input v-model="formData.rydaBh" readonly v-trim maxlength="100" v-if="type === 'add'">
              <template #append>
                <el-button @click="choosePersonneFileHandle">
                  <SvgIcon name="ele-Search" />
                </el-button>
              </template>
            </el-input>
            <span v-else>{{ formData.rydaBh }}</span>
          </el-form-item>
        </vp-col>
        <vp-col :span="3">
          <el-form-item prop="rydaXm">
            <template #label><vp-label zh="姓名" en="Name" align="left" /></template>
            <el-input v-model="formData.rydaXm" readonly v-if="type === 'add'"></el-input>
            <span v-else>{{ formData.rydaXm }}</span>
          </el-form-item>
        </vp-col>

        <vp-col :span="1">
          <el-form-item prop="bz">
            <template #label><vp-label zh="备注" en="remark" align="left" /></template>
            <el-input type="textarea" v-model="formData.bz" v-trim maxlength="1000" v-if="isEditPage"></el-input>
            <span v-else>{{ formData.bz }}</span>
          </el-form-item>
        </vp-col>
      </el-row>
    </vp-card>

    <vp-card>
      <template #header>
        <vp-label zh="授权课程" en="Authorized course" />
      </template>
      <el-row>
        <vp-table :data="formData.courseList" style="flex:2;margin-left: 10px;height: 255px;overflow-y: auto;"
          height="250" row-key="kczid">
          <el-table-column min-width="150">
            <template #header><vp-label zh="课程编号" en="Course No." /></template>
            <template #default="scope">
              <el-form-item :prop="`courseList[${scope.$index}].courseBh`" label-width="auto">
                <span>{{ scope.row.courseBh }}</span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column min-width="150">
            <template #header><vp-label zh="课程名称" en="Course Name" /></template>
            <template #default="scope">
              <el-form-item :prop="`courseList[${scope.$index}].courseName`" label-width="auto">
                <span>{{ scope.row.courseName }}</span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column min-width="150">
            <template #header>
              <div style="display: flex;align-items: center;gap: 10px;">
                <vp-label zh="授权有效期" en="Authorization Term" />
                <div @click="handleDialogRqOpen">
                  <SvgIcon name="ele-Calendar" :size="24" />
                </div>
              </div>
            </template>
            <template #default="scope">
              <el-form-item :prop="`courseList[${scope.$index}].sqrq`" :rules="formRules.courseList.sqrq"
                label-width="auto">
                <el-date-picker style="width:100%" start-placeholder="开始日期/Start Date" end-placeholder="结束日期/End Date"
                  type="daterange" range-separator="-" v-model="scope.row.sqrq" v-if="isEditPage"
                  value-format="YYYY-MM-DD" unlink-panels
                  @change="handleScheduleShrSj($event, scope.row)"></el-date-picker>
                <span v-else>{{ scope.row.sqksrq }}-{{ scope.row.sqjsrq }}</span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" width="100" v-if="isEditPage">
            <template #header>
              <el-button circle @click="handleAddCourse()">
                <SvgIcon name="ele-Plus"></SvgIcon>
              </el-button>
            </template>
            <template #default="scope">
              <el-button circle @click="handleDeleteCourse(scope.$index)">
                <SvgIcon name="ele-Minus"></SvgIcon>
              </el-button>
            </template>
          </el-table-column>
        </vp-table>
      </el-row>
    </vp-card>

    <VpFileListCard :attachmentList="formData.attachments" @attachmentListEmit="getAttachmentListEmit($event, formData)"
      :readOnly="!(isEditPage)">
      <template #header>
        <vp-label zh="附件" en="Attachment" />
      </template>
    </VpFileListCard>


    <el-dialog v-model="dialogRqVisible" title="统一授权有效期" width="500" :append-to-body="true" :destroy-on-close="true"
      :close-on-click-modal="false">
      <template #title>
        <vp-label zh="统一授权有效期" en="Validity period of unified authorization" align="left" />
      </template>
      <el-form-item label-width="140px">
        <template #label><vp-label zh="统一有效期" en="Uniform validity period" align="left" /></template>
        <el-date-picker style="width:100%" type="daterange" range-separator="-" start-placeholder="Start date"
          end-placeholder="End date" v-model="tonyiRq" value-format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <vp-btn-cancel @click="handleDialogRqClose" />
          <vp-btn-confirm @click="handleDialogRqPrimary" />
        </div>
      </template>
    </el-dialog>
    <VpPersonnelFileDialog ref="vpPersonnelFileDialogRef"></VpPersonnelFileDialog>
    <VpCourseMultDialog ref="vpCourseMultDialogRef" @confirm="handleCourseMultConfirmed"></VpCourseMultDialog>
  </el-form>
</template>
<script setup lang="ts" name="TrainingTeacher">
import { defineAsyncComponent, onMounted, ref, watch, computed } from "vue";
import request from "/@/utils/request";
import validateUtils from "/@/utils/validateUtils";
import VpFileListCard from '/@/components/vp/file/VpFileListCard.vue';


import VpCourseMultDialog from '/@/components/vp/course/VpCourseMultDialog.vue';
import VpPersonnelFileDialog from '/@/components/vp/personnelFile/VpPersonnelFileDialog.vue';
import { ElMessage } from 'element-plus';

const emits = defineEmits(['formSubmited']);

const formData = ref({
  id: "",
  rydaid: "",
  bz: "",
  rydaBh: "",
  rydaXm: "",
  courseList: [] as any[],
  fjglid: "",
  attachments: [],
});
const formRules = {
  rydaBh: [
    validateUtils.notNull,
  ],
  rydaXm: [
    validateUtils.notNull
  ],
  courseList: {
    kczid: [validateUtils.notNull],
    sqksrq: [validateUtils.notNull],
    sqjsrq: [validateUtils.notNull],
    sqrq: [validateUtils.notNull],
  }
}

const tonyiRq = ref([]);
//统一日期设置好的 
const tonyiRqSetting = ref([]);

const initFormData = () => {
  formData.value = {
    id: "",
    rydaid: "",
    bz: "",
    rydaBh: "",
    rydaXm: "",

    courseList: [] as any[],

    fjglid: "",
    attachments: [],
  }
}

const type = ref('add');
const loading = ref(false);
const formRef = ref();

const props = defineProps<{
  id: string,
  type: string,
}>()

onMounted(() => {
  handleOpen(props.type, props.id);
})

// 是否是编辑页面
const isEditPage = computed(() => {
  return props.type === 'add' || props.type === 'edit';
});

const handleOpen = (_type: string, id: string) => {
  type.value = _type;
  initFormData();
  if (type.value != "add") {
    loading.value = true;
    request.get(`/training/teacher/${id}`).then((res) => {
      formData.value = {
        ...formData.value,
        ...res.data,
      };

      //处理课程的日期
      formData.value.courseList.forEach((item: any) => {
        item.sqrq = [item.sqksrq,item.sqjsrq];
      });

      loading.value = false;
      emits("formSubmited", formData.value);
    });
  }
}

// 选择人员档案
const vpPersonnelFileDialogRef = ref();
const choosePersonneFileHandle = () => {
  vpPersonnelFileDialogRef.value.handleOpen({
    selected: formData.value.rydaid,
    callback: (data: any) => {
      formData.value.rydaid = data.id;
      formData.value.rydaBh = data.bh;
      formData.value.rydaXm = data.xm;
    }
  });
}

//课程选择
const vpCourseMultDialogRef = ref()
const handleAddCourse = () => {
  vpCourseMultDialogRef.value.handleOpen();
}
const handleCourseMultConfirmed = (data: any) => {

  const sqrqCopy = tonyiRqSetting.value ? [...tonyiRqSetting.value] : null;
  const sqksrqCopy = tonyiRqSetting?.value[0] ? tonyiRqSetting.value[0] : "";
  const sqjsrqCopy = tonyiRqSetting?.value[1] ? tonyiRqSetting.value[1] : "";
  //x循环data 构建新的参数
  let newData = data.map((item: any) => {
    return {
      kczid: item.zid,
      courseBh: item.bh,
      courseName: item.mcZw,
      kcmc: item.mcZw,
      sqksrq: sqksrqCopy,
      sqjsrq: sqjsrqCopy,
      sqrq: sqrqCopy,
    }
  })
  formData.value.courseList = newData;
}

const handleDeleteCourse = (index: number) => {
  formData.value.courseList.splice(index, 1);
}

const getAttachmentListEmit = (list: any, row: any) => {
  row.attachments = list;
}

//全局日期
const dialogRqVisible = ref(false);
const handleDialogRqOpen = () => {
  dialogRqVisible.value = true;
  tonyiRq.value = tonyiRqSetting.value;

}
const handleDialogRqClose = () => {
  tonyiRqSetting.value = [];
  tonyiRq.value = [];
  dialogRqVisible.value = false;
}
const handleDialogRqPrimary = () => {
  dialogRqVisible.value = false;
  tonyiRqSetting.value = tonyiRq.value;


  //循环修改courseList 里面的时间
  formData.value.courseList.forEach((item: any) => {
    item.sqksrq = tonyiRqSetting.value[0];
    item.sqjsrq = tonyiRqSetting.value[1];
    item.sqrq = tonyiRqSetting.value;
  })
}

//时间处理
const handleScheduleShrSj = (list: any, row: any) => {
  row.sqksrq = row.sqrq[0];
  row.sqjsrq = row.sqrq[1];
}

const getData = (zt: number): Promise<any> => {
  let promise = new Promise((resolve, reject) => {
    formRef.value.validate((valid: boolean) => {
      if (valid) {
        if (formData.value.courseList.length == 0) {
          ElMessage.error("⾄少有⼀条授权课程/There is at least one authorized course");
          reject();
        }
        resolve({
          ...formData.value,
        });
      } else {
        reject();
      }
    })
  })
  return promise;
};


defineExpose({
  getData
})

</script>
<style scoped>
:deep(.row-warning1) {
  color: var(--el-color-danger);
}
</style>